package com.runningfox.humor;

import java.net.URI;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.FrameLayout.LayoutParams;

import com.admob.android.ads.AdManager;
import com.admob.android.ads.AdView;
import com.admob.android.ads.AdManager.Gender;
import com.admob.android.ads.AdView.AdListener;
import com.runningfox.Process.ChangeUserNameProcess;
import com.runningfox.Process.DeleteFavouriteJokeProcess;
import com.runningfox.Process.DisLikeProcess;
import com.runningfox.Process.HomePageProcess;
import com.runningfox.Process.LikeProcess;
import com.runningfox.Process.LoadAllJokesProcess;
import com.runningfox.Process.LoadFavouriteJokesProcess;
import com.runningfox.Process.LoadJokeProcess;
import com.runningfox.Process.LoadReadedJokesProcess;
import com.runningfox.Process.LoadUnreadJokesProcess;
import com.runningfox.Process.MoreJokesProcess;
import com.runningfox.Process.RefreshHomePageProcess;
import com.runningfox.Process.SendCommentProcess;
import com.runningfox.Process.SyncJokeProcess;
import com.runningfox.logic.Cache;
import com.runningfox.logic.Logic;
import com.runningfox.model.Comment;
import com.runningfox.model.Joke;
import com.runningfox.model.ResultSet;
import com.runningfox.model.Setting;

/**
 * @author lhy Project page: http://code.google.com/p/humor/
 */
public class Humor extends Activity implements Callback, AdListener {

	/** Called when the activity is first created. */
	public static final int LAYER_DETAIL = 4;
	public static final int LAYER_COMMENT = 5;
	public static final int LAYER_COMMENT_EDITNAME = 6;
	public static final int LAYER_SETTING = 7;
	public static final int LAYER_LIST = 8;
	public int curLayer = LAYER_LIST;
	public boolean menuFlag = false;
	public int lastLayer = -1;
	TextView txtPreTop, txtNextTop, txtBackTop;
	TextView txtPre,txtNext,txtBack;
	LinearLayout listLayer, noticeLayer,commentLayer;// detailLayer;
	LinearLayout btnAll, btnUnread, btnFavourite, btnHistory;
	LinearLayout btnAllNormal, btnUnreadNormal, btnFavouriteNormal,
			btnHistoryNormal;
	Button imgSend, imgCommentClose;

	ProcessPool pool;
	int selected = -1;
	ListView jokeList;// , commentList;
	ListView jokeDetail;
	JokeListAdapter jokeListAdapter;
	JokeDetailListAdapter jokeDetailAdapter;
	public TextView txtLoading, txtStatus;
	public EditText editComment;
	public View listheaderview;
	public LinearLayout btnsLayout;
	Context c;
	ListLayerCtrl listCtrl;
	DetailLayerCtrl detailCtrl;
	InputMethodManager imm;// = (InputMethodManager)
	View navView,navViewTop;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		Window win = getWindow();
		win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
		setContentView(R.layout.main1);
		c = this.getApplicationContext();
		Cache.DIR = c.getDir("cache", 0);
		Cache.HOME = c.getDir("home", 0);
		Logic.c = c;
		this.btnAll = (LinearLayout) this.findViewById(R.id.LinearLayoutAll);
		this.btnUnread = (LinearLayout) this
				.findViewById(R.id.LinearLayoutUnread);
		this.btnFavourite = (LinearLayout) this
				.findViewById(R.id.LinearLayoutFavourite);
		this.btnHistory = (LinearLayout) this
				.findViewById(R.id.LinearLayoutHistory);

		this.btnAllNormal = (LinearLayout) this
				.findViewById(R.id.LinearLayoutAll0);
		this.btnUnreadNormal = (LinearLayout) this
				.findViewById(R.id.LinearLayoutUnread0);
		this.btnFavouriteNormal = (LinearLayout) this
				.findViewById(R.id.LinearLayoutFavourite0);
		this.btnHistoryNormal = (LinearLayout) this
				.findViewById(R.id.LinearLayoutHistory0);

		this.btnAllNormal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				actionLoadAllJokes();
			}

		});

		this.btnFavouriteNormal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				actionLoadFavouriteJokes();
			}

		});
		this.btnHistoryNormal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				actionLoadReadJokes();
			}

		});
		this.btnUnreadNormal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				actionLoadUnReadJokes();
			}

		});
		// this.imgBanner=(ImageView) this.findViewById(R.id.imgbanner);
		this.txtStatus = (TextView) this.findViewById(R.id.txtStatus);
		this.txtLoading = (TextView) this.findViewById(R.id.txtLoading);
		this.listLayer = (LinearLayout) this.findViewById(R.id.ListLayer);
		this.noticeLayer = (LinearLayout) this.findViewById(R.id.noticeLayer);
		this.detailCtrl = new DetailLayerCtrl(this);
		jokeList = (ListView) this.findViewById(R.id.ListJoke);

		btnsLayout = (LinearLayout) this.findViewById(R.id.btnsLayout);

		jokeListAdapter = new JokeListAdapter(this);
		jokeList.setAdapter(jokeListAdapter);
		this.listCtrl = new ListLayerCtrl(this, jokeListAdapter);
		jokeList.setOnTouchListener(this.listCtrl);
		jokeList.setOnItemClickListener(this.listCtrl);
		jokeList.setOnItemSelectedListener(this.listCtrl);
		pool = new ProcessPool();
		pool.start();
		this.actionLoadAllJokes();

		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		// Gender g= new Gender();
		if (Setting.gender == 0) {
			AdManager.setGender(Gender.FEMALE);
		} else {
			AdManager.setGender(Gender.MALE);
		}
		adlist = (AdView) findViewById(R.id.adlist);
		adlist.setListener(this);

		if (Setting.autoConnect) {
			this.actionHomePage();
		} else {
			this.txtStatus.setTextColor(Color.GRAY);
			this.txtStatus.setVisibility(View.VISIBLE);
			this.txtStatus.setText(this.getString(R.string.offline));
			this.noticeLayer.bringToFront();
		}
		display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		w = display.getWidth();
		h = display.getHeight();

		this.jokeList
				.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, h - 117));
		this.jokeDetail = (ListView) this.findViewById(R.id.ListDetail);
		LayoutInflater inf = LayoutInflater.from(c);
		navView = inf.inflate(R.layout.listnav, null);
		jokeDetail.addFooterView(navView);
		
		navViewTop = inf.inflate(R.layout.listnav, null);
//		jokeDetail.addHeaderView(navViewTop);
		this.jokeDetailAdapter = new JokeDetailListAdapter(this);
		this.jokeDetail.setAdapter(jokeDetailAdapter);
		this.jokeDetail.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, h - 117));
		this.txtNext = (TextView) this.navView.findViewById(R.id.txtNext);
		this.txtPre = (TextView) this.navView.findViewById(R.id.txtPre);
		this.txtBack = (TextView) this.navView.findViewById(R.id.txtBack);

		this.txtNext.setOnClickListener(this.detailCtrl);
		this.txtPre.setOnClickListener(this.detailCtrl);
		this.txtBack.setOnClickListener(this.detailCtrl);

		this.txtBack.setOnTouchListener(this.detailCtrl);
		this.txtPre.setOnTouchListener(this.detailCtrl);
		this.txtNext.setOnTouchListener(this.detailCtrl);

		
		this.txtNextTop = (TextView) this.navViewTop.findViewById(R.id.txtNext);
		this.txtPreTop = (TextView) this.navViewTop.findViewById(R.id.txtPre);
		this.txtBackTop = (TextView) this.navViewTop.findViewById(R.id.txtBack);

		this.txtNextTop.setOnClickListener(this.detailCtrl);
		this.txtPreTop.setOnClickListener(this.detailCtrl);
		this.txtBackTop.setOnClickListener(this.detailCtrl);

		this.txtBackTop.setOnTouchListener(this.detailCtrl);
		this.txtPreTop.setOnTouchListener(this.detailCtrl);
		this.txtNextTop.setOnTouchListener(this.detailCtrl);
		
		this.editComment=(EditText) this.findViewById(R.id.editComment);
		this.imgSend =(Button) this.findViewById(R.id.ImageSend);
		this.imgCommentClose=(Button) this.findViewById(R.id.ImageClose);
		this.editComment.setOnClickListener(detailCtrl);
		this.imgSend.setOnClickListener(detailCtrl);
		this.imgCommentClose.setOnClickListener(detailCtrl);
		this.commentLayer = (LinearLayout) this.findViewById(R.id.layoutcomment);
	}

	public AdView adlist;// ,addetail;
	MenuItem itemRefresh, itemSetting,itemUpdate,itemFeedBack,itemPost;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.detailmenu, menu);
		this.itemRefresh = menu.findItem(R.id.itemRefresh);
		this.itemSetting = menu.findItem(R.id.itemSetting);
		this.itemUpdate =menu.findItem(R.id.itemUpdate);
		this.itemFeedBack=menu.findItem(R.id.itemFeedback);
		this.itemPost=menu.findItem(R.id.itemPost);
		this.itemRefresh.setVisible(true);
		this.itemSetting.setVisible(true);
		this.itemUpdate.setVisible(true);
		this.itemFeedBack.setVisible(true);
		this.itemPost.setVisible(true);
		this.menuFlag = true;
		return true;
	}

	int w;
	int h;
	Display display;
	LayoutParams param = new LayoutParams(LayoutParams.FILL_PARENT,
			LayoutParams.FILL_PARENT);

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		w = display.getWidth();
		h = display.getHeight();
		this.listLayer.setLayoutParams(param);
		// this.detailLayer.setLayoutParams(param);
		// this.webView.setLayoutParams(new
		// android.widget.LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,h-73));
		this.jokeList
				.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, h - 117));
		this.jokeDetail
				.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, h - 117));
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		// TODO Auto-generated method stub
		this.itemRefresh.setVisible(true);
		this.itemSetting.setVisible(true);
		this.itemUpdate.setVisible(true);
		this.itemFeedBack.setVisible(true);
		this.itemPost.setVisible(true);
		this.menuFlag = true;
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		int id = item.getItemId();
		switch (id) {
		case R.id.itemRefresh: {
			// 刷新笑话页面
			if (this.curLayer == LAYER_DETAIL) {
				// this.actionRefreshJoke(this.detailCtrl.curNode);
				this.actionLoadJoke(this.detailCtrl.curNode);
			} else {
				// 刷新首页
				this.actionHomePage();
				this.actionRefreshHomePage();
			}
			break;
		}
		case R.id.itemSetting: {
			this.lastLayer = this.curLayer;
			this.actionShowSettingLayer();
			break;
		}
		case R.id.itemUpdate:{
			String url="market://search?q=runningfox";
			Uri uri =Uri.parse(url);
			Intent it = new Intent();
			it.setAction(Intent.ACTION_VIEW);
			it.setData(uri);
			this.startActivity(it);
			break;
		}
		case R.id.itemFeedback:{
			Intent it = new Intent(Intent.ACTION_SENDTO,Uri.parse("mailto:hitlhy@gmail.com"));
			it.putExtra(Intent.EXTRA_SUBJECT, this.getString(R.string.feedback));
			this.startActivity(it);
			break;
		}
		case R.id.itemPost:{
			Intent it = new Intent(Intent.ACTION_SENDTO,Uri.parse("mailto:hitlhy@gmail.com"));
			it.putExtra(Intent.EXTRA_SUBJECT,Setting.name+":" + this.getString(R.string.tellyouajoke));
			this.startActivity(it);
			break;
		}
		}
		this.menuFlag = false;
		return super.onOptionsItemSelected(item);
	}

	public void actionShowSettingLayer() {
		// TODO Auto-generated method stub
		this.curLayer = this.LAYER_SETTING;
		Intent intent = new Intent(Humor.this, Settings.class);
		startActivity(intent);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// if (keyCode == KeyEvent.KEYCODE_BACK
		// && (this.curLayer != this.LAYER_ALL
		// || this.curLayer != this.LAYER_FAVOURITE || this.curLayer !=
		// this.LAYER_UNREAD)) {
		// return true;
		// }
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		// return true;
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (this.menuFlag) {
				this.menuFlag = false;
				return super.onKeyUp(keyCode, event);
			} else if (this.flag_share) {
				this.flag_share = false;
				return super.onKeyUp(keyCode, event);
			} else if (this.curLayer == LAYER_DETAIL) {
				this.actionActiveListLayer();
				return true;
			} else if (this.curLayer == LAYER_COMMENT_EDITNAME) {
				this.actionActiveCommentLayer();
				return true;
			} else if (this.curLayer == LAYER_COMMENT) {
				this.actionActiveDetailLayer();
				return true;
			} else if (this.curLayer == LAYER_LIST) {
				this.finish();
				return true;
			} else if (this.curLayer == LAYER_SETTING) {
				this.actionActiveListLayer();
				return true;
			}
		}

		return super.onKeyUp(keyCode, event);
	}

	boolean isOnline = false;

	public void actionStatusOnline() {
		this.txtStatus.setVisibility(View.VISIBLE);
		if (Setting.wifi != null)
			this.txtStatus.setText(this.getString(R.string.online) + "@"
					+ Setting.wifi);
		else {
			this.txtStatus.setText(this.getString(R.string.online) + "@");
		}
		// #ccf04d
		this.txtStatus.setTextColor(Color.rgb(0xcc, 0xf0, 0x4d));
		this.noticeLayer.bringToFront();
		isOnline = true;
	}

	public void actionStatusOffline() {
		this.txtStatus.setVisibility(View.VISIBLE);
		this.txtStatus.setText(this.getString(R.string.offline));
		// #ccf04d
		this.txtStatus.setTextColor(Color.GRAY);
		this.noticeLayer.bringToFront();
		isOnline = false;
	}

	public void actionHideStatus() {
		this.txtStatus.setVisibility(View.GONE);
	}

	public void actionRefreshHomePage() {
		pool.execute(new RefreshHomePageProcess(this.handler));
	}

	public void actionHomePage() {
		pool.execute(new HomePageProcess(this.handler));
	}

	public void syncJokes() {
		pool.execute(new SyncJokeProcess(this.handler));
	}

	public void actionHideTopBtns() {
		this.btnsLayout.setVisibility(View.GONE);
		// this.imgAd.setVisibility(View.VISIBLE);
	}

	public void actionShowTopBtns() {
		this.btnsLayout.setVisibility(View.VISIBLE);
	}

	/**
	 * 从网络读取下一组笑话
	 * 
	 * @param handler
	 */
	// public void actionLoadMore(Handler handler) {
	// if (this.curLayer == LAYER_ALL) {
	// pool.execute(new MoreJokesProcess(handler,
	// this.jokeListAdapter.page));
	// }
	// }
	/**
	 * 从本地数据库中读取未读的笑话
	 * 
	 * @param handler
	 */
	public void actionLoadUnReadJokes() {
		if (ListLayerCtrl.curLayer != ListLayerCtrl.LAYER_UNREAD) {
			pool.execute(new LoadUnreadJokesProcess(handler));
		}
	}

	/**
	 * 从本地数据库中读取已读的笑话
	 */
	public void actionLoadReadJokes() {
		if (ListLayerCtrl.curLayer != ListLayerCtrl.LAYER_HISTORY) {
			pool.execute(new LoadReadedJokesProcess(handler));
		}
	}

	/**
	 * 从本地数据库中读取所有笑话
	 */
	public void actionLoadAllJokes() {
		pool.execute(new LoadAllJokesProcess(this.handler));
	}

	/**
	 * 从本地数据库中读取加星的笑话
	 * 
	 * @param handler
	 */
	public void actionLoadFavouriteJokes() {
		if (ListLayerCtrl.curLayer != ListLayerCtrl.LAYER_FAVOURITE)
			pool.execute(new LoadFavouriteJokesProcess(handler));
	}

	public void actionLike(Joke node) {
		if (this.isOnline) {
			pool.execute(new LikeProcess(handler, node));
		}
	}

	public void actionDislike(Handler handler, int id) {
		pool.execute(new DisLikeProcess(handler, id));
	}

	// public void actionOld(Handler handler, Joke node) {
	// pool.execute(new OldProcess(handler, node));
	// }

	public void actionActiveDetailLayer() {
		// this.listLayer.setVisibility(View.GONE);
		// this.detailLayer.setVisibility(View.VISIBLE);
		// this.commentEditLayer.setVisibility(View.GONE);
		// this.optionBtnLayer.setVisibility(View.VISIBLE);
		// this.imageLayer.setVisibility(View.GONE);
		this.jokeList.setVisibility(View.GONE);
		this.jokeDetail.setVisibility(View.VISIBLE);
		this.txtStatus.setVisibility(View.GONE);
		this.commentLayer.setVisibility(View.GONE);
		if(this.detailCtrl.curNode!=null){//刻舟求剑
			this.checkPreNextLink(this.detailCtrl.curNode);
		}
		this.curLayer = LAYER_DETAIL;
	}

	public void actionActiveListLayer() {
		// this.actionLoadAllJokes();
		this.listLayer.setVisibility(View.VISIBLE);
		this.jokeDetail.setVisibility(View.GONE);
		this.jokeList.setVisibility(View.VISIBLE);
		this.txtBack.setVisibility(View.GONE);
		this.txtNext.setVisibility(View.GONE);
		this.txtPre.setVisibility(View.GONE);
		
		this.txtBackTop.setVisibility(View.GONE);
		this.txtNextTop.setVisibility(View.GONE);
		this.txtPreTop.setVisibility(View.GONE);
		// this.detailLayer.setVisibility(View.GONE);
		// this.imageLayer.setVisibility(View.GONE);

		this.curLayer = LAYER_LIST;
		this.commentLayer.setVisibility(View.GONE);
		// this.actionActiveTab(LAYER_ALL);
	}

	// public void actionCommentBtnPressed() {
	// this.imgComment.setVisibility(View.GONE);
	// this.txtComment.setTextColor(Color.YELLOW);
	// this.txtComment.setTextSize(20);
	// }
	//
	// public void actionCommentBtnReleased() {
	// this.imgComment.setVisibility(View.VISIBLE);
	// this.txtComment.setTextColor(Color.WHITE);
	// this.txtComment.setTextSize(18);
	// }
	//
	// public void actionShareBtnPressed() {
	// this.imgShare.setVisibility(View.GONE);
	// this.txtShare.setTextColor(Color.YELLOW);
	// this.txtShare.setTextSize(20);
	// }
	//
	// public void actionShareBtnReleased() {
	// this.imgShare.setVisibility(View.VISIBLE);
	// this.txtShare.setTextColor(Color.WHITE);
	// this.txtShare.setTextSize(18);
	// }
	//
	// public void actionRefreshBtnPressed() {
	// this.imgRefresh.setVisibility(View.GONE);
	// this.txtRefresh.setTextColor(Color.YELLOW);
	// this.txtRefresh.setTextSize(20);
	// }
	//
	// public void actionRefreshBtnReleased() {
	// this.imgRefresh.setVisibility(View.VISIBLE);
	// this.txtRefresh.setTextColor(Color.WHITE);
	// this.txtRefresh.setTextSize(14);
	// }
	//
	// public void actionLikeBtnPressed() {
	// this.imgFavourite.setVisibility(View.GONE);
	// this.txtLike.setTextColor(Color.YELLOW);
	// this.txtLike.setTextSize(20);
	// }
	//
	// public void actionLikeBtnReleased() {
	// this.imgFavourite.setVisibility(View.VISIBLE);
	// this.txtLike.setTextColor(Color.WHITE);
	// this.txtLike.setTextSize(18);
	// }
	//
	// public void actionBackBtnPressed() {
	// this.imgBack.setVisibility(View.GONE);
	// this.txtBack.setTextColor(Color.YELLOW);
	// this.txtBack.setTextSize(20);
	// }
	//
	// public void actionBackBtnReleased() {
	// this.imgBack.setVisibility(View.VISIBLE);
	// this.txtBack.setTextColor(Color.WHITE);
	// this.txtBack.setTextSize(18);
	// }

//	AlertDialog commentDlg;

	/**
	 * 显示编辑评论页面
	 */
	public void actionActiveCommentLayer() {
		this.curLayer = LAYER_COMMENT;
		this.commentLayer.setVisibility(View.VISIBLE);
		this.commentLayer.bringToFront();
	}

	/**
	 * 编辑用户名称
	 */
	public void actionActiveEditNameLayer() {
		// TODO Auto-generated method stub
		this.curLayer = LAYER_COMMENT_EDITNAME;
	}

	/**
	 * 提交评论
	 * 
	 * @param node
	 * @param comment
	 */
	public void actionSendComment(Joke node, String comment) {
		this.imm.hideSoftInputFromWindow(this.editComment.getWindowToken(), 0);
		pool.execute(new SendCommentProcess(handler, node, comment));
	}

	// public void actionShowDetailView() {
	// this.optionBtnLayer.setVisibility(View.VISIBLE);
	// this.commentEditLayer.setVisibility(View.GONE);
	// this.webView.setVisibility(View.VISIBLE);
	// // this.commentList.setVisibility(View.GONE);
	// this.curLayer = this.LAYER_DETAIL;
	// }

	/**
	 * 显示loading条 停止loading条使用actionFinishLoading
	 * 
	 * @param charSequence
	 */
	public void actionShowLoading(CharSequence charSequence) {
		this.noticeLayer.setVisibility(View.VISIBLE);
		this.txtLoading.setText(charSequence);
		this.noticeLayer.bringToFront();
	}

	/**
	 * 停止显示loading条 打开loading条使用actionShowLoading
	 */
	public void actionFinishLoading() {
		this.noticeLayer.setVisibility(View.GONE);
		this.txtLoading.setText("");
	}

	public void actionShowTip(CharSequence charSequence) {
		Toast.makeText(c, charSequence, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 加载笑话
	 * 
	 * @param node
	 */
	public void actionLoadJoke(Joke node) {
		if (this.isOnline)
			pool.execute(new LoadJokeProcess(this.handler, node));
	}

	/**
	 * 加载jokenode的前一个笑话
	 * 
	 * @param node
	 */
	public void actionLoadPreJoke(Joke node) {
		Joke prenode = this.jokeListAdapter.getPreNode(node);
		if (prenode != null) {
			pool.execute(new LoadJokeProcess(this.handler, prenode));
		} else {
			this.actionShowTip(this.getText(R.string.nomore));
		}
		// checkPreNextLink(prenode);
	}

	void checkPreNextLink(Joke node) {
		Joke pre = this.jokeListAdapter.getPreNode(node);
		Joke next = this.jokeListAdapter.getNextNode(node);
		if (pre != null) {
			this.txtPre.setVisibility(View.VISIBLE);
			this.txtPreTop.setVisibility(View.VISIBLE);
		} else {
			this.txtPre.setVisibility(View.GONE);
			this.txtPreTop.setVisibility(View.GONE);
		}

		if (next != null) {
			this.txtNext.setVisibility(View.VISIBLE);
			this.txtNextTop.setVisibility(View.VISIBLE);
		} else {
			this.txtNext.setVisibility(View.GONE);
			this.txtNextTop.setVisibility(View.GONE);
		}
		this.txtBack.setVisibility(View.VISIBLE);
		this.txtBackTop.setVisibility(View.VISIBLE);
	}

	/**
	 * 加载jokenode的后一个笑话
	 * 
	 * @param node
	 */
	public void actionLoadNextJoke(Joke node) {
		Joke nextnode = this.jokeListAdapter.getNextNode(node);
		if (nextnode != null) {
			pool.execute(new LoadJokeProcess(this.handler, nextnode));
		} else {
			this.actionShowTip(this.getText(R.string.nomore));
		}
	}

	public void actionRefreshJoke(Joke node) {
		if (node != null) {//
			this.jokeListAdapter.updateNode(node);
			this.jokeListAdapter.notifyDataSetChanged();
			this.jokeDetailAdapter.updateNode(node);
			this.jokeDetailAdapter.notifyDataSetChanged();
		}
	}

	public boolean loadMoreDone = true;

	public boolean hasMoreJokes = true;

	/**
	 * 加载更多
	 */
	public void actionLoadMoreJokes() {
		// long time = this.jokeListAdapter.getLastItem().datetime;
		int hid = this.jokeListAdapter.getMinHid();
		if (this.loadMoreDone
				&& ListLayerCtrl.curLayer == ListLayerCtrl.LAYER_ALL && hid > 0
				&& this.hasMoreJokes) {
			pool.execute(new MoreJokesProcess(handler, String.valueOf(hid)));
			this.loadMoreDone = false;
		}
	}

	/**
	 * 更新笑话首页缓存
	 * 
	 * @param list
	 */
	public void actionUpateCache1(ArrayList<Joke> list) {
		Logic.updateAllJokes(list);
	}

	// public static void post(Context ct, Bitmap bitmap) {
	// Uri uri = saveImage(bitmap, ct);
	//
	// // Uri uri = Uri.parse("file://"+path);
	// Intent it = new Intent(Intent.ACTION_SEND);
	// it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
	// Log.i("zhoubo", uri.toString());
	// it.putExtra(Intent.EXTRA_STREAM, uri);
	// it.setType("image/jpg");
	// ct.startActivity(Intent.createChooser(it, "Choose Email Client"));
	// }

	boolean flag_share = false;

	/**
	 * 分享笑话
	 * 
	 * @param node
	 */
	public void actionShareJoke(Joke node) {
		flag_share = true;
		Intent it = new Intent(Intent.ACTION_SEND);
		it.putExtra(Intent.EXTRA_TEXT, node.body);
		it.setType("text/plain");
		this.startActivity(Intent.createChooser(it, this
				.getString(R.string.shareby)));
	}

	/**
	 * 修改用户名
	 * 
	 * @param name
	 */
	public void actionChangeUserName(String name) {
		pool.execute(new ChangeUserNameProcess(this.handler, name));
	}

	/**
	 * 
	 * @param index
	 */
	public void actionActiveTab(int index) {
		this.btnAll.setVisibility(View.GONE);
		this.btnUnread.setVisibility(View.GONE);
		this.btnFavourite.setVisibility(View.GONE);
		this.btnHistory.setVisibility(View.GONE);
		this.txtBack.setVisibility(View.GONE);
		this.txtPre.setVisibility(View.GONE);
		this.txtNext.setVisibility(View.GONE);
		
		this.txtBackTop.setVisibility(View.GONE);
		this.txtNextTop.setVisibility(View.GONE);
		this.txtPreTop.setVisibility(View.GONE);
		// this.imageLayer.setVisibility(View.GONE);
		this.commentLayer.setVisibility(View.GONE);
		this.btnAllNormal.setVisibility(View.VISIBLE);
		this.btnUnreadNormal.setVisibility(View.VISIBLE);
		this.btnFavouriteNormal.setVisibility(View.VISIBLE);
		this.btnHistoryNormal.setVisibility(View.VISIBLE);

		this.jokeDetail.setVisibility(View.GONE);
		this.jokeList.setVisibility(View.VISIBLE);
		this.curLayer = LAYER_LIST;
		switch (index) {
		case ListLayerCtrl.LAYER_ALL: {
			this.btnAll.setVisibility(View.VISIBLE);
			this.btnAllNormal.setVisibility(View.GONE);
			ListLayerCtrl.curLayer = ListLayerCtrl.LAYER_ALL;
			break;
		}
		case ListLayerCtrl.LAYER_UNREAD: {
			this.btnUnread.setVisibility(View.VISIBLE);
			this.btnUnreadNormal.setVisibility(View.GONE);
			ListLayerCtrl.curLayer = ListLayerCtrl.LAYER_UNREAD;
			break;
		}
		case ListLayerCtrl.LAYER_FAVOURITE: {
			this.btnFavourite.setVisibility(View.VISIBLE);
			this.btnFavouriteNormal.setVisibility(View.GONE);
			ListLayerCtrl.curLayer = ListLayerCtrl.LAYER_FAVOURITE;
			break;
		}
		case ListLayerCtrl.LAYER_HISTORY: {
			this.btnHistory.setVisibility(View.VISIBLE);
			this.btnHistoryNormal.setVisibility(View.GONE);
			ListLayerCtrl.curLayer = ListLayerCtrl.LAYER_HISTORY;
			break;
		}
		}
	}

	Handler handler = new Handler(this);

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.Handler.Callback#handleMessage(android.os.Message)
	 */
	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		Bundle buddle = msg.getData();
		switch (msg.what) {
		case Action.CHANGEUSERNAME: {
			ResultSet res = (ResultSet) buddle.get("res");
			Setting.name = res.user.name;
			Setting.email = res.user.email;
			Setting.saveSetting(this);
			// if (this.curLayer == LAYER_COMMENT_EDITNAME) {
			this.actionActiveCommentLayer();
			// }
			break;
		}
		case Action.CHANGEUSERNAMEFAIL: {
			this.actionShowTip(this.getText(R.string.usernamedupliacated));
			break;
		}
		case Action.CACHEHIT: {
			// this.actionShowTip("cache hit");
			break;
		}
		case Action.CAHCEMISS: {
			// this.actionShowTip("cache miss");
			break;
		}
		case Action.CAHCEREFRESH: {
			// this.actionShowTip("refresh");
			break;
		}
		case Action.HOME: {
			int size = buddle.getInt("size");
			this.actionActiveTab(ListLayerCtrl.LAYER_ALL);
			this.actionLoadAllJokes();
			this.loadMoreDone = true;
			// int t_size = this.jokeListAdapter.getCount() - size;
			// this.txtStatus.setText(this.getText(R.string.online));
			// this.txtStatus.setVisibility(View.VISIBLE);
			this.actionStatusOnline();
			this.noticeLayer.bringToFront();
			break;
		}

		case Action.LOADUNREAD: {
			ArrayList<Joke> list = (ArrayList<Joke>) buddle.get("list");
			this.jokeListAdapter.setList(list);
			this.actionActiveTab(ListLayerCtrl.LAYER_UNREAD);
			break;
		}

		case Action.LOADREAD: {
			ArrayList<Joke> list = (ArrayList<Joke>) buddle.get("list");
			this.jokeListAdapter.setList(list);
			this.actionActiveTab(ListLayerCtrl.LAYER_HISTORY);
			break;
		}
		case Action.LOADFAVOURITE: {
			ArrayList<Joke> list = (ArrayList<Joke>) buddle.get("list");
			this.jokeListAdapter.setList(list);
			this.actionActiveTab(ListLayerCtrl.LAYER_FAVOURITE);
			break;
		}

		case Action.LOADJOKE: {
			Joke node = buddle.getParcelable("joke");
			this.detailCtrl.curNode = node;
			ArrayList list = new ArrayList();
			list.add(node);
			this.jokeDetailAdapter.setList(list);
			actionActiveDetailLayer();
			break;
		}
		case Action.LOADCOMMENT: {
			ArrayList<Comment> comments = buddle
					.getParcelableArrayList("comments");
			ArrayList list = new ArrayList();
			list.add(this.detailCtrl.curNode);
			list.addAll(comments);
			this.detailCtrl.curNode.comment=String.valueOf(comments.size());
			this.actionRefreshJoke(this.detailCtrl.curNode);
			this.jokeDetailAdapter.setList(list);
			this.jokeDetailAdapter.notifyDataSetChanged();
			this.actionActiveDetailLayer();
			break;
		}

		case Action.HTTP200: {
			this.actionShowLoading(this.getText(R.string.connect));
			this.actionStatusOnline();
			break;
		}
		case Action.HTTPFAIL: {
			this.actionShowTip(this.getText(R.string.cannotconnect));
			this.actionStatusOffline();
			break;
		}
		case Action.HTTP500: {
			this.actionShowTip(this.getText(R.string.servererror));
			break;
		}
		case Action.PARSING: {
			this.actionShowLoading(this.getText(R.string.parsing));
			break;
		}
		case Action.PARSEFAILED: {
			this.actionShowTip(this.getText(R.string.parseerro));
			break;
		}
		case Action.SYNCFAILED: {
			break;
		}
		case Action.SYNCSUCEED: {
			ArrayList<Joke> list = (ArrayList<Joke>) buddle.get("res");
			this.jokeListAdapter.setList(list);
			this.actionActiveTab(ListLayerCtrl.LAYER_ALL);
			break;
		}
		case Action.MORELOCAL: {
			ArrayList<Joke> list = (ArrayList<Joke>) buddle.get("res");
			this.jokeListAdapter.appendList(list);
			this.actionActiveTab(ListLayerCtrl.LAYER_ALL);
			break;
		}
		case Action.MORENET: {
			ArrayList<Joke> list = (ArrayList<Joke>) buddle.get("list");
			int size = buddle.getInt("size");
			if (list.size() == 0) {
				this.hasMoreJokes = false;
			} else {
				this.jokeListAdapter.appendList(list);
				this.loadMoreDone = true;
				int t_size = size - this.jokeListAdapter.getCount();
				if (size >= 0) {
					this.txtStatus.setText(this.getText(R.string.thereis)
							.toString()
							+ t_size
							+ this.getText(R.string.jokesleft).toString());
					this.txtStatus.setVisibility(View.VISIBLE);
					this.noticeLayer.bringToFront();
				}
			}
			this.actionActiveTab(ListLayerCtrl.LAYER_ALL);
			break;
		}
		case Action.NOTLOADEDHOMEPAGE: {
			// Toast.makeText(c, "home page is old", Toast.LENGTH_SHORT).show();
			break;
		}
		case Action.LOADHOMEPAGEFAIL: {
			// Toast.makeText(c, "home page is failed",
			// Toast.LENGTH_SHORT).show();
			this.txtStatus.setTextColor(Color.GRAY);
			this.txtStatus.setText(this.getString(R.string.offline));
			this.txtStatus.setVisibility(View.VISIBLE);
			this.noticeLayer.bringToFront();
			break;
		}
		case Action.STARTLOADING: {
			this.actionShowLoading(this.getText(R.string.loading));
			break;
		}
		case Action.ENDLOADING: {
			this.actionFinishLoading();
			break;
		}
		case Action.LOADALL: {
			ArrayList<Joke> list = (ArrayList<Joke>) buddle.get("list");
			this.jokeListAdapter.setList(list);
			// if (list.size() > 0) {
			// Toast.makeText(c, list.size() + " jokes loaded from cache",
			// Toast.LENGTH_SHORT).show();
			// } else {
			// Toast.makeText(c, "cache empty", Toast.LENGTH_SHORT).show();
			// }
			this.actionActiveTab(ListLayerCtrl.LAYER_ALL);
			break;
		}
		case Action.LIKE: {
			this.actionRefreshJoke(this.detailCtrl.curNode);
			break;
		}
		}
		return true;
	}

	protected void loadWebPage(String html, final WebView v) {
		v.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
	}

	/**
	 * 删除收藏
	 * 
	 * @param node
	 */
	public void actionDeleteFavouriteJoke(Joke node) {
		// TODO Auto-generated method stub
		if (node != null) {
			pool.execute(new DeleteFavouriteJokeProcess(this.handler, node));
		}
	}

	public String actionCacheImage(String url) {
		// TODO Auto-generated method stub
		return Logic.getCacheImage(url);
	}

	/**
	 * 图片
	 */
	Bitmap bitmap;

	/**
	 * 显示图片
	 * 
	 * @param url
	 */
	public void actoinShowImageLayer(String url) {
		String imageFilePath = url;
		if (url.startsWith("file:///")) {
			imageFilePath = url.substring(7);
		}

		bitmap = BitmapFactory.decodeFile(imageFilePath);
		if (bitmap == null) {
			this.actionShowTip(imageFilePath + " not found!");
		}
		// imgZoom.setImageBitmap(bitmap);
		// this.findViewById(R.id.imageLayer).setVisibility(View.VISIBLE);
		// this.findViewById(R.id.imageLayer).bringToFront();
		this.listLayer.setVisibility(View.GONE);
		// this.detailLayer.setVisibility(View.GONE);
		// this.imageLayer.setVisibility(View.VISIBLE);
		// this.imageLayer.bringToFront();
	}

	/**
	 * 缩放图片
	 * 
	 * @param sx
	 * @param sy
	 */
	public void actionUpdateImageScale(float sx, float sy) {
		float width = this.bitmap.getWidth();
		float height = this.bitmap.getHeight();
		float newwidth = width * sx;
		float newheight = height * sy;
		// imgZoom.setImageBitmap(zoomResImage(this.bitmap, (int) newwidth,
		// (int) newheight));
	}

	/***
	 * 图片的缩放方法
	 * 
	 * @param bgimage
	 *            ：源图片资源
	 * @param newWidth
	 *            ：缩放后宽度
	 * @param newHeight
	 *            ：缩放后高度
	 * @return
	 */
	public static Bitmap zoomResImage(Bitmap bgimage, int newWidth,
			int newHeight) {
		// 获取这个图片的宽和高
		int width = bgimage.getWidth();
		int height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算缩放率，新尺寸除原始尺寸
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, width, height,
				matrix, true);
		return bitmap;
	}

	public void actionShowMenu() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onFailedToReceiveAd(AdView adView) {
		// TODO Auto-generated method stub
		// this.adlist.setVisibility(View.GONE);
		// 不要在这里操作adview 会产生
		// android.view.ViewRoot$CalledFromWrongThreadException: Only the
		// original thread that created a view hierarchy can touch its views.
		// 导致详细内容无法显示的bug
		// adView.setVisibility(View.GONE);
		// this.handler.sendEmptyMessage(Action.LOADADFAIL);
		Log.v("onFailedToReceiveAd", "onFailedToReceiveAd");
	}

	@Override
	public void onNewAd() {
		// TODO Auto-generated method stub
		Log.v("onNewAd", "onNewAd");
		this.adlist.bringToFront();
		// this.adlist.setVisibility(View.VISIBLE);
	}

	@Override
	public void onReceiveAd(AdView adView) {
		// TODO Auto-generated method stub
		Log.v("onReceiveAd", "onReceiveAd");
		// this.adlist.setVisibility(View.VISIBLE);
		adView.setVisibility(View.VISIBLE);
		adView.bringToFront();
		// this.handler.sendEmptyMessage(Action.LOADAD);

		// this.imgBanner.setVisibility(View.INVISIBLE);
	}
}